package com.vortex.cloud.sample.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vortex.cloud.sample.domain.TaskUser;
import com.vortex.cloud.sample.domain.TaskUserInfo;
import com.vortex.cloud.sample.dto.ExcelMessageTaskUserInfoDTO;
import com.vortex.cloud.sample.dto.TaskUserDemoExcelDTO;
import com.vortex.cloud.sample.mapper.ExcelDemoMapper;
import com.vortex.cloud.sample.service.ExcelDemoService;
import com.vortex.cloud.vfs.lite.base.dto.excel.ExcelMessageDTO;
import com.vortex.cloud.vfs.lite.base.dto.excel.ExcelReadDTO;
import com.vortex.cloud.vfs.lite.base.util.ExcelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-10-18 周一
 * @time 11:49
 * @description
 */
@Service
public class ExcelDemoServiceImpl extends ServiceImpl<ExcelDemoMapper, TaskUser> implements ExcelDemoService {

    @Resource
    private ExcelDemoService excelDemoService;

    @Override
    public List<ExcelMessageDTO> importExcel(MultipartFile file, Integer startRowNum, Integer startCellNum) {
        ExcelReadDTO<TaskUserDemoExcelDTO> readDto = ExcelUtils.readExcel(file, TaskUserDemoExcelDTO.class, startRowNum, startCellNum);
        // 如果数据格式验证不通过，则直接返回给前端
        if (CollectionUtils.isNotEmpty(readDto.getMessages())) {
            return readDto.getMessages();
        }
        List<TaskUser> taskUsers = readDto.getDatas().stream().map(entity -> {
            TaskUser taskUser = new TaskUser();
            // 把 第一个类的字段 复制到 第二类的字段上
            BeanUtils.copyProperties(entity, taskUser);
            return taskUser;
        }).collect(Collectors.toList());
        //不为空时，插入到数据库中
        if (CollectionUtils.isNotEmpty(taskUsers)) {
            excelDemoService.saveBatch(taskUsers);
        }
        return readDto.getMessages();
    }
}
